<?php
namespace Admin\Models\ask;

use Helpers\Hrm;
use Phalcon\Di;
use Helpers\User;
use Admin\Models\BaseModel;
use Admin\Models\user\XhsysUser;

class XhaskSurvey extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iASId;

    /**
     *
     * @var string
     */
    public $mAQId;

    /**
     *
     * @var string
     */
    public $sTitle;

    /**
     *
     * @var string
     */
    public $mExplain;

    /**
     *
     * @var string
     */
    public $sRemind;

    /**
     *
     * @var integer
     */
    public $bDisable;

    /**
     *
     * @var integer
     */
    public $bMutable;

    /**
     *
     * @var string
     */
    public $sThanksMsg;

    /**
     * @var integer
     */
    public $iCompleteNum;

    /**
     *
     * @var integer
     * @enum 1=学校，2=公司
     */
    public $iTarget;

    /**
     *
     * @var string
     */
    public $sSchoolId;

    /**
     *
     * @var string
     */
    public $sUserType;

    /**
     *
     * @var string
     */
    public $sClassName;

    /**
     *
     * @var string
     */
    public $sDepId;

    /**
     *
     * @var string
     */
    public $sUserId;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var integer
     */
    public $iStartTime;

    /**
     *
     * @var integer
     */
    public $iEndTime;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var integer
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;

    /**
     *
     * @var integer
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHAsk_Survey';
    }

    /**
     * 格式更改
     *
     * @return bool
     *
     * create by ck 20171212
     * modify by ck 20171215
     * modify by ck 20190123    增加班级字段
     */
    public function beforeSave()
    {
        $arr = ['mAQId', 'sUserId', 'sSchoolId', 'sUserType', 'sDepId', 'sClassName'];
        foreach ($arr as $field) {
            $this->$field = trim($this->$field, ',');
            if ($this->$field && $this->$field != 'all') {
                $this->$field = ',' . $this->$field . ',';
            }
            if (in_array($field, ['sSchoolId', 'sUserType', 'sDepId', 'sClassName']) && !$this->$field) {
                $this->$field = 'all';
            }
        }
//        $this->mAQId = trim($this->mAQId, ',');
//        if ($this->mAQId) {
//            $this->mAQId = ',' . $this->mAQId . ',';
//        }
//        $this->sUserId    = ',' . trim($this->sUserId, ',') . ',';
//        $this->sSchoolId  = ',' . trim($this->sSchoolId, ',') . ',';
//        $this->sUserType  = ',' . trim($this->sUserType, ',') . ',';
        return true;
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhaskSurvey[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhaskSurvey
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 获取用户未参加问卷列表
     *
     * @param null $userId
     * @param null $schoolId
     * @param null $userType
     * @return mixed
     * @throws \Exception
     *
     * create by ck 20171212
     * modify by ck 20180208    优化用户查询
     * modify by ck 20180416    添加提示语查询
     * modify by ck 20190123    增加班级查询
     */
    public static function getAllowAttendList($userId = null, $schoolId = null, $userType = null)
    {
        $userId or $userId = User::getId();
        if (!$schoolId || !$userType || $userType == 1) {
            $user = XhsysUser::findFirst([
                'columns'    => 'iUserId,iSchoolId,iUserType,sAdClsName',
                'conditions' => 'iUserId = :userId:',
                'bind'       => ['userId' => $userId]
            ]);
            if (!$user) {
                throw new \Exception('无用户id或未登录');
            }
            $schoolId = $user->iSchoolId;
            $userType = $user->iUserType;
            $className = $user->sAdClsName;
        }
        $nowTime = time();
        $db  = Di::getDefault()->get('db');
        $sql = "SELECT
                  iASId AS id,
                  sTitle AS title,
                  mExplain AS `explain`,
                  sRemind AS remind,
                  iCompleteNum AS completeNum,
                  iStartTime AS startTime,
                  iEndTime AS endTime
                FROM XHAsk_Survey
                WHERE (sUserId LIKE '%,{$userId},%')
                  OR (
                    sUserId = ''
                    AND (sSchoolId LIKE '%,{$schoolId},%' OR sSchoolId = 'all')
                    AND (sUserType = 'all' OR sUserType LIKE '%,{$userType},%' )
                    AND (sClassName = 'all' OR sClassName LIKE '%,{$className},%')
                  )
                  AND bDelete = 0 AND bDisable = 0 AND iStartTime < '{$nowTime}' AND iEndTime > '{$nowTime}' AND iTarget = 1
                  AND iASId NOT IN (SELECT iASId FROM XHAsk_SurveyInfo WHERE iUserId = '{$userId}')";
        return $db->fetchAll($sql);
    }

    /**
     * 获取公司内部问卷
     *
     * @param null $userId
     * @return mixed
     *
     * create by ck 20180408
     */
    public static function getStaffSurvey($userId = null)
    {
        $userId or $userId = User::getId();
        $depIds       = Hrm::getDepId($userId, true);
        $depCondition = ["sDepId = 'all'"];
        foreach ($depIds as $depId) {
            $depCondition[] = "sDepId LIKE '%,{$depId},%'";
        }
        $depCondition = implode(' OR ', $depCondition);
        $nowTime      = time();
        $sql = "SELECT
                  iASId AS id,
                  sTitle AS title,
                  mExplain AS `explain`,
                  sRemind AS remind,
                  iCompleteNum AS completeNum,
                  iStartTime AS startTime,
                  iEndTime AS endTime
                FROM XHAsk_Survey
                WHERE (sUserId LIKE '%,{$userId},%') 
                  OR (
                    sUserId = ''
                    AND ($depCondition)
                  ) 
                  AND bDelete = 0 AND bDisable = 0 AND iStartTime < '{$nowTime}' AND iEndTime > '{$nowTime}' AND iTarget = 2
                  AND iASId NOT IN (SELECT iASId FROM XHAsk_SurveyInfo WHERE iUserId = '{$userId}')";
        return Di::getDefault()->get('db')->fetchAll($sql);
    }

//    /**
//     * 根据数据及id字段获取记录
//     *
//     * @param $data
//     * @return XhaskSurvey
//     * @throws \Exception
//     *
//     * create by ck 20171212
//     */
//    public static function getModel($data)
//    {
//        $idField = 'iCCId';
//        if (isset($data[$idField]) && $data[$idField]) {
//            $obj = self::findFirst($data[$idField]);
//            if (!$obj) {
//                throw new \Exception('该id下无记录');
//            }
//        }
//        isset($obj) or $obj = new self();
//        $obj->assign($data);
//        $obj->iStartTime = strtotime($obj->iStartTime) ?: time();
//        $obj->iEndTime   = strtotime($obj->iEndTime);
//        return $obj;
//    }

    /**
     * 根据传入id，删除对应记录并返回删除结果
     *
     * @param $ids
     * @return mixed
     *
     * create by ck 20160926
     */
//    public static function deleteRecordById($ids){
//        return self::find(array(
//            'conditions' => "iASId IN ({$ids}) AND bDelete = 0"
//        ))->delete();
//    }

    /**
     * 根据数据及服务人员ID创建对象并返回
     *
     * @param $data
     * @param $serverId
     * @return XhaskSurvey
     *
     * create by ck 20160726
     * modify by ck 20160926    简化
     */
//    public static function createRecord($data, $serverId)
//    {
//        $obj = new self;
//        $obj->assign($data);
//        $obj->iCompleteNum  = 0;
////        $obj->iServerId     = $serverId;
//        return $obj;
//    }

    /**
     * @param $serverId
     * @return XhaskSurvey
     * 根据服务人员ID获取问卷信息
     * add by ck 20160726
     */
//    public static function getSurveyByServerId($serverId)
//    {
//        $nowTime = date('Y-m-d H:i:s');
//        return self::findFirst(array(
//            'conditions'    =>  'iServerId=:iServerId: AND bDelete=0 AND bAskEnable=1 AND tStartTime<=:tNowTime: AND tEndTime>=:tNowTime:',
//            'bind'          => array(
//                'iServerId'     => $serverId,
//                'tNowTime'      => $nowTime
//            ),
////            'bindTypes'      => array(
////                'iServerId'     => \Phalcon\Db\Column::BIND_PARAM_INT,
////                'tNowTime'      => \Phalcon\Db\Column::BIND_PARAM_STR
////            )
//        ));
//    }

}
